/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 30/11/13
 * Time: 12:39
 * To change this template use File | Settings | File Templates.
 */
var mongoose = require('mongoose');
var when = require('when');

var schemas = require('../schemas/index.js');
var schema = schemas['media'];

var model = mongoose.model('media', schema);

function create(data) {
    var deferred = when.defer();
    var Model = new model();
    Object.keys(data).forEach(function(key) {
        Model[key] = data[key];
    });
    Model.save(function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function getList(page, limit) {
    var t = Date.now();
    page = page - 1;
    limit = limit || 10;
    var deferred = when.defer();
    var query = model.find();
    query.sort({
        created : -1
    });
    query.limit(limit);
    query.skip(page * limit);
    query.exec(function(err, medias) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(medias);
            console.log('Medias getList 查询费时' + (Date.now() - t) + 'ms');
            t = null;
        }
    });
    return deferred.promise;
}

function update(id, data, callback) {
    delete data._id;
    model.findByIdAndUpdate(id, data, {
        multi : false,
        safe : true
    }, callback);
}

function findById(id, callback) {
    model.findById(id, callback);
}

module.exports = {
    'create' : create,
    'getList' : getList,
    'update' : update,
    'findById' : findById
};
